package com.fenxiangle.yueding.feature.login.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.widget.dialog.ActionSheetDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnOperItemClickL;
import com.fenxiangle.yueding.entity.bo.LoginPram;
import com.fenxiangle.yueding.entity.bo.QQUserInfoBo;
import com.fenxiangle.yueding.entity.bo.WbUserBo;
import com.fenxiangle.yueding.entity.bo.WxUserBo;
import com.fenxiangle.yueding.feature.common.view.MainActivity;
import com.fenxiangle.yueding.feature.login.contract.LoginContract;
import com.fenxiangle.yueding.feature.login.dependencies.login.DaggerLoginComponent;
import com.fenxiangle.yueding.feature.login.dependencies.login.LoginPresenterModule;
import com.fenxiangle.yueding.framework.api.ApiLib;
import com.suozhang.framework.component.http.Host;
import com.suozhang.framework.entity.bo.UserInfoBo;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.HttpRootSelectUtils;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.suozhang.framework.widget.HintDialog;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * Created by Home on 2018/9/1.
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {


    @BindView(R.id.login_phone)
    EditText mLoginPhone;
    @BindView(R.id.login_btn_code)
    TextView mLoginBtnCode;
    @BindView(R.id.login_code)
    EditText mLoginCode;
    private UMShareAPI mShareAPI;
    WxUserBo mWxUserInfoBo;
    private boolean isHOme;

    @Inject
    LoginContract.Presenter mPresenter;
    private int mType;
    private ActionSheetDialog dialog;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {
        DaggerLoginComponent.builder().loginPresenterModule(new LoginPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ImageView view2 = findViewById(R.id.view2);
        view2.animate().setDuration(500).rotation(180).start();
        isHOme = this.getIntent().getBooleanExtra("is_home", false);

    }

    @Override
    protected void initData() {
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        mShareAPI = UMShareAPI.get(this);
        mShareAPI.setShareConfig(config);
    }
    @Override
    protected void initEvent() {

    }


    /**
     * 重新设置主机头
     *
     * @param host
     */
    private void resetHost(Host host) {
        ApiLib.resetHost(host);
        initInjector();
    }

    @OnClick({R.id.login_btn_code, R.id.btn_login, R.id.btn_login_sina, R.id.btn_login_qq, R.id.btn_login_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn_code:
                mPresenter.sendCode(mLoginPhone.getText().toString());
                break;
            case R.id.btn_login:
                mPresenter.userLogin(mLoginPhone.getText().toString(), mLoginCode.getText().toString(), JPushInterface.getRegistrationID(this));
                break;
            case R.id.btn_login_sina:
                mType = 2;
                loginWb();
                break;
            case R.id.btn_login_qq:
                mType = 3;
                loginQQ();
                break;
            case R.id.btn_login_wx:
                mType = 1;
                initUmLoginWx(SHARE_MEDIA.WEIXIN);
                break;

        }
    }

    @Override
    public void showBindReferee(UserInfoBo s) {
        Intent intent = new Intent(this, RecommendPeopleActivity.class);
        intent.putExtra("user_uid", s.getUserUid());
        startActivity(intent);
        finish();
    }

    @Override
    public void showLoginSuccess() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void showBindPhone(UserInfoBo s) {
        Intent intent = new Intent(this, BindingPhoneActivity.class);
        intent.putExtra("user_uid", s.getUserUid());
        startActivity(intent);
        finish();
    }


    @Override
    public void showCodeSuccess(LoginPram s) {
        T.showShort("获取验证码成功!");
//        mLoginCode.setText(s.getCode());
        onGetCode();
    }

    public void onGetCode() {
        final int count = 60;//倒计时10秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return count - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mLoginBtnCode.setEnabled(false);
                        mLoginBtnCode.setTextColor(AM.res().getColor(R.color.primary_comparison));
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long num) {

                mLoginBtnCode.setText(num + "s");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //回复原来初始状态
                mLoginBtnCode.setEnabled(true);
                mLoginBtnCode.setText("发送验证码");
                mLoginBtnCode.setTextColor(AM.res().getColor(R.color.primary_comparison));
            }
        });

    }


    @Override
    public void showError(String error) {
        showMsg(error);
    }

    private void initUmLoginWx(final SHARE_MEDIA type) {
        try {
            if (!mShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN)) {
                T.showShort("您未安装微信！");
                return;
            }
        } catch (Exception e) {
            showMsg(e.getMessage());
        }


        mShareAPI.getPlatformInfo(LoginActivity.this, type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                showLoading();
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map == null) return;
                mWxUserInfoBo = JSONObject.parseObject(JSON.toJSONString(map), WxUserBo.class);
                if (mWxUserInfoBo != null) {
                    mPresenter.userThirdLogin(
                            mWxUserInfoBo.getOpenid(),
                            mType,
                            mWxUserInfoBo.getGender().equals("男") ? 0 : 1,
                            mWxUserInfoBo.getName(),
                            mWxUserInfoBo.getProfile_image_url(), JPushInterface.getRegistrationID(LoginActivity.this));
                }

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                dismissLoading();
                T.showShort(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                dismissLoading();
            }
        });
    }

    private void loginWb() {
        mShareAPI.getPlatformInfo(this, SHARE_MEDIA.SINA, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map == null) return;
                WbUserBo wbUserBo = JSONObject.parseObject(JSON.toJSONString(map), WbUserBo.class);
                mPresenter.userThirdLogin(wbUserBo.getUid(), mType,
                        mWxUserInfoBo.getGender().equals("男") ? 0 : 1,
                        wbUserBo.getScreen_name(), wbUserBo.getIconurl(), JPushInterface.getRegistrationID(LoginActivity.this));
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                Logger.e("--------------?" + throwable.getMessage());
                showMsg(throwable.getMessage() + "");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

    private void loginQQ() {

        mShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                if (map == null) return;
                QQUserInfoBo wbUserBo = JSONObject.parseObject(JSON.toJSONString(map), QQUserInfoBo.class);
                mPresenter.userThirdLogin(wbUserBo.getOpenid(), mType, wbUserBo.getGender().equals("男") ? 0 : 1,
                        wbUserBo.getScreen_name(), wbUserBo.getIconurl(), JPushInterface.getRegistrationID(LoginActivity.this));
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                showMsg(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                showMsg("已取消!");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }




    private int count = 0;
    private boolean isOk = false;

    @OnClick(R.id.btn_choose)
    public void onVersionClicked() {
        if (!AM.isDebug()) {
            return;
        }
        count++;
        //连续点击5次 弹出选择框
        if (count >= 5) {
            isOk = true;
            showMsg("Test mode enabled!");
        }
    }

    @OnLongClick(R.id.btn_choose)
    public boolean onVersionLongClicked() {
        if (isOk) {
            count = 0;
            isOk = false;
            showHostSelector();
        }
        return true;
    }

    private void showHostSelector() {
        HttpRootSelectUtils.selectHttpRoot(this, new HttpRootSelectUtils.ResetHostListener() {
                    @Override
                    public void onResetHost(Host host) {
                        resetHost(host);
                        showMsg("切换成功");
                    }
                },
                null);
    }
}
